/*
 * Admin Action
 */
var CKL     = require("../utils/checklogin"),
Response    = require("../utils/response"),
DaoMysql    = require('../models/dao-mysql').DaoMysql,
CacheRedis  = require('../models/cache-redis').CacheRedis,
User        = require('../models/user').User;
Passenger   = require('../models/passenger').Passenger;
Page        = require('../models/page').Page;
Tariff        = require('../models/tariff').Tariff;
var fs = require('fs');

module.exports = function(app){	
	var dao = new DaoMysql(app.envConfig.dbMysql, app.mysqlClient, app.logmessage, new CacheRedis(app.envConfig.storeRedis, app.redisClient, app.logmessage, app.defs.DEFAULT_CACHE_EXPIRE_SECS));
	var setting;
	
	//读取配置文件
	fs.readFile('./config/setting.json',function(err,data){
	    if(err)app.logmessage("load setting.json :"+err);
	    setting = JSON.parse(data);
	});

	//进入Admin首页
	app.get(app.envConfig.routes.admin.url,CKL.logined);
	app.get(app.envConfig.routes.admin.url,function(req,res){
		var msg=req.flash('info').toString();
		Response.render(app,res,app.envConfig.routes.admin.page,{user:req.session.user,info:msg});
	});
	
	//退出登录
	app.get(app.envConfig.routes.admin_logout.url, function(req,res){
		req.session.user=null;
		return Response.redirect(app,res,app.envConfig.routes.admin_logout.redirect);
	});
	
	//修改密码
	app.post(app.envConfig.routes.admin_update.url,CKL.logined);
	app.post(app.envConfig.routes.admin_update.url,function(req,res){
		if(req.body.newpwd=="" || req.body.newpwd1=="" || req.body.oldpwd==""){
			 return Response.jsonerror(app,res,{msg:"修改失败,请填写完整"});
		}
		if(req.body.newpwd!=req.body.newpwd1){
			 return Response.jsonerror(app,res,{msg:"修改失败,两次密码不一致"});
		}
		dao.get(User, req.body.id, function(err,result){
			if(err || !result){
				 return Response.jsonerror(app,res,{msg:"修改失败,用户不存在"});
			}
			 if(result.password !=req.body.oldpwd){
				 return Response.jsonerror(app,res,{msg:"修改失败,原始密码错误"});
	        }
			result.password=req.body.newpwd;
			dao.update(new User(result), function(err,result){
				if(err || !result){
					 return Response.jsonerror(app,res,{msg:"修改失败"});
				}else{
					 return Response.jsonsuccess(app,res,{msg:"修改成功"});
				}
			});
		});
	});
	
	//用户列表POST
	app.post(app.envConfig.routes.admin_user_list.url,CKL.logined);
	app.post(app.envConfig.routes.admin_user_list.url, function(req,res){		
		listuser(req,res);
	});
	
	//用户列表GET
	app.get(app.envConfig.routes.admin_user_list.url,CKL.logined);
	app.get(app.envConfig.routes.admin_user_list.url, function(req,res){		
		listuser(req,res);
	});
	
	//设置
	app.get(app.envConfig.routes.admin_setting.url,CKL.logined);
	app.get(app.envConfig.routes.admin_setting.url, function(req,res){		
		var msg=req.flash('msg');
		Response.render(app,res,app.envConfig.routes.admin_setting.page,{user:req.session.user,setting:setting,msg:msg});
	});
	
	//保存设置
	app.post(app.envConfig.routes.admin_setting_save.url,CKL.logined);
	app.post(app.envConfig.routes.admin_setting_save.url, function(req,res){
		 console.log(req);
	    var t_path = req.files.tapp.path;
	    var c_path = req.files.capp.path;
	    setting.phone=req.body.phone;
	    setting.t_app_v=req.body.tappv;
	    setting.c_app_v=req.body.cappv;
	    setting.gg=req.body.gg;
	    if(t_path){
	    	if(req.files.tapp.size>0){
	    		setting.t_app_u="upload/"+req.files.tapp.name;
	 	       var t_target_path = app.envConfig.server.upload_dir + req.files.tapp.name;
	 	       fs.rename(t_path, t_target_path, function(err) {
	 	 	      if (err) console.log(err);
	 	 	      fs.unlink(t_path, function() {
	 	 	         if (err) console.log(err);
	 	 	         res.send('File uploaded to: ' + t_target_path + ' - ' + req.files.tapp.size + ' bytes');
	 	 	      });
	 	 	    }); 
	    	}else{
	    		fs.unlink(t_path, function() {
 	 	      	});
	    	}
	    }
	    if(c_path){
	    	if(req.files.capp.size>0){
	    		setting.c_app_u="upload/"+req.files.capp.name;
	    	  	var c_target_path = app.envConfig.server.upload_dir + req.files.capp.name;
	    	  	fs.rename(c_path, c_target_path, function(err) {
		 	      if (err) console.log(err);
		 	      fs.unlink(c_path, function() {
		 	         if (err)console.log(err);
		 	         res.send('File uploaded to: ' + c_target_path + ' - ' + req.files.capp.size + ' bytes');
		 	      });
	    	  	}); 
	    	}else{
	    		fs.unlink(c_path, function() {
		 	   	});
	    	}
	    }
		fs.writeFile('./config/setting.json', JSON.stringify(setting),function(err){
		        if(!err){
		        	console.log('save setting finished');
		        }else{
		        	console.log(err);
		        }
		       
		 });
		req.flash("msg","保存成功");
		return Response.redirect(app,res,app.envConfig.routes.admin_setting_save.redirect);
	});
	
	//用户查询方法
	function listuser(req,res){
		if(!req.body.pageNo){
			req.body.pageNo=0;
		}
		if(!req.body.pageSize){
			req.body.pageSize=5;
		}
		dao.searchPage(User,"role=0",req.body.pageNo+","+req.body.pageSize,function(err,result,total){
			if(err){
				console.log(err);
			}
			var page=new Page(req.body.pageNo,req.body.pageSize,result,total);
			Response.render(app,res,app.envConfig.routes.admin_user_list.page,{user:req.session.user,page:page});
		});
	}
	
	//收费表
	app.get(app.envConfig.routes.admin_tariff.url,CKL.logined);
	app.get(app.envConfig.routes.admin_tariff.url,function(req,res){
		dao.search(Tariff,"",function(err,result,total){
			if(err){
				console.log(err);
			}
			Response.render(app,res,app.envConfig.routes.admin_tariff.page,{user:req.session.user,tariff:result});
		});
	});
	
	//添加修改收费表
	app.post(app.envConfig.routes.admin_tariff_upload.url,CKL.logined);
	app.post(app.envConfig.routes.admin_tariff_upload.url,function(req,res){
		var t_path = req.files.img.path;
		Tariff.id = req.body.id;
		Tariff.start = req.body.start;
		Tariff.end = req.body.end;
		if(req.body.id && req.body.vs){
			Tariff.vs=parseInt(req.body.vs)+1;
		}else{
			Tariff.vs=0;
		}
	    if(t_path){
	    	if(req.files.img.size>0){
	    	   Tariff.img ="upload/"+req.files.img.name;
	 	       var t_target_path = app.envConfig.server.upload_dir + req.files.img.name;
	 	       fs.rename(t_path, t_target_path, function(err) {
	 	 	      if (err) console.log(err);
	 	 	      fs.unlink(t_path, function() {
	 	 	         
	 	 	      });
	 	 	    }); 
	    	}else{
	    		fs.unlink(t_path, function() {
 	 	      	});
	    	}
	    }else{
	    	if(req.body.id){
	    		Tariff.img=req.body.image;
	    	}
	    }
	    if(req.body.id){
	    	dao.update(new Tariff(Tariff), function(err,result){
				if(err || !result){
					return Response.redirect(app,res,app.envConfig.routes.admin_tariff.url);
				}else{
					return Response.redirect(app,res,app.envConfig.routes.admin_tariff.url);
				}
			});
	    }else{
	    	dao.create(new Tariff(Tariff), function(err,result){
				if(err || !result){
					return Response.redirect(app,res,app.envConfig.routes.admin_tariff.url);
				}else{
					return Response.redirect(app,res,app.envConfig.routes.admin_tariff.url);
				}
			});
	    }
	});
	
	//删除收费表
	app.get(app.envConfig.routes.admin_tariff_del.url,CKL.logined);
	app.get(app.envConfig.routes.admin_tariff_del.url,function(req,res){
		if(req.params.id){
			dao.remove(Tariff,req.params.id, function(err,result){
				if(err){
					return Response.jsonerror(app,res,{msg:"删除失败"});
				}else{
					return Response.jsonsuccess(app,res,{msg:"删除成功"});
				}
			});
		}else{
			return Response.jsonerror(app,res,{msg:"删除失败,参数错误"});
		}
	});
	
	//查询收费表
	app.get(app.envConfig.routes.admin_tariff_get.url,CKL.logined);
	app.get(app.envConfig.routes.admin_tariff_get.url,function(req,res){
		if(req.params.id){
			dao.get(Tariff,req.params.id,function(err,result){
				if(err || !result){
					 return Response.jsonerror(app,res,{msg:"无数据"});
				}else{
					 return Response.jsonsuccess(app,res,result);
				}
			});
		}
	});
	
	
	
	//乘客列表POST
	app.post(app.envConfig.routes.passenger_list.url,CKL.logined);
	app.post(app.envConfig.routes.passenger_list.url, function(req,res){		
		listpassenger(req,res);
	});
	
	//乘客列表GET
	app.get(app.envConfig.routes.passenger_list.url,CKL.logined);
	app.get(app.envConfig.routes.passenger_list.url, function(req,res){		
		listpassenger(req,res);
	});
	
	//用户查询方法
	function listpassenger(req,res){
		if(!req.body.pageNo){
			req.body.pageNo=0;
		}
		if(!req.body.pageSize){
			req.body.pageSize=5;
		}
		dao.searchPage(Passenger,"",req.body.pageNo+","+req.body.pageSize,function(err,result,total){
			if(err){
				console.log(err);
			}
			var page=new Page(req.body.pageNo,req.body.pageSize,result,total);
			Response.render(app,res,app.envConfig.routes.passenger_list.page,{user:req.session.user,page:page});
		});
	}
	
	
	//乘客禁止，启用操作
	app.get(app.envConfig.routes.passenger_competence.url,CKL.logined);
	app.get(app.envConfig.routes.passenger_competence.url,function(req,res){
		if(req.params.id){
				dao.get(Passenger,req.params.id,function(err,result){
					if(err || !result){
						 return Response.jsonerror(app,res,{msg:"审核失败"});
					}else{
						if(result.canuse == 1)
						{
							result.canuse = 0;
						}
						else
						{
							result.canuse = 1;
						}
						dao.update(new Passenger(result), function(err,result){
							if(err || !result){
								return Response.jsonerror(app,res,{msg:"审核失败"});
							}else{
								return Response.jsonsuccess(app,res,{msg:"审核成功"});
							}
						}); 
					}
				});
		}else{
			return Response.jsonerror(app,res,{msg:"审核失败,参数错误"});
		}
	});
};